//index.js
const img = require('../../utils/img.js')
const ctx = wx.createCanvasContext('shareImg');

Page({
  cdx: 0, // 窗口宽度

  /**
   * 页面的初始数据
   */
  data: {
    prurl: '',

    defaultImg: '',

    userInfo: {},
    hasUserInfo: false,

    list: []
  },

  changeList: function (e) {
    let that = this
    switch (e.target.dataset.list) {
      case 'hot':
        this.setData({
          list: that.data.hot
        })
        break;
      case 'national':
        this.setData({
          list: that.data.national
        })
        break;
      default:
        this.setData({
          list: []
        });
        break;
    }
  },

  selectImg: function (e) {
    var current = e.target.dataset.src;
    this.setData({
      defaultImg: current,
      prurl: ''
    });

    this.initCanvas(this.data.defaultImg);
  },

  // 初始化
  initCanvas(imgUrl) {
    let that = this;
    // console.log("Promise.all", res)
    //主要就是计算好各个图文的位置
    let num = 150;
    // ctx.drawImage(res[0].path, 0, 0, num, num)
    ctx.drawImage(imgUrl, this.cdx, 0, num, num)
    ctx.rect(this.cdx, 0, num + 1, num + 1)
    ctx.stroke()
    ctx.draw(false, () => {
      wx.canvasToTempFilePath({
        x: this.cdx,
        y: 0,
        width: num,
        height: num,
        destWidth: 960,
        destHeight: 960,
        canvasId: 'shareImg',
        success: function (res) {
          that.setData({
            prurl: res.tempFilePath
          })
          // wx.hideLoading()
        },
        fail: function (res) {
          wx.hideLoading()
        }
      })
    })
  },


  // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
  // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
  getUserProfile(e) {
    let avatarUrl = ''
    let that = this;
    if (!that.data.userInfo.avatarUrl) {
      wx.showLoading({
        title: '生成中',
      })
      console.log('-- 1 --');
      wx.getUserProfile({
        desc: '仅用于生成头像使用', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: (res) => {
          console.log(JSON.stringify(res.userInfo));
          that.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
          avatarUrl = this.headimgHD(res.userInfo.avatarUrl)
          that.drawImg(avatarUrl);
          wx.hideLoading()
        },
        fail: () => {
          wx.hideLoading()
        }
      });
    } else if (that.data.userInfo.avatarUrl) {
      console.log('-- 2 --');
      avatarUrl = this.headimgHD(that.data.userInfo.avatarUrl)
      that.drawImg(avatarUrl);
    }
  },

  headimgHD(imageUrl) {
    imageUrl = imageUrl.split('/');    //把头像的路径切成数组
    //把大小数值为 46 || 64 || 96 || 132 的转换为0
    if (imageUrl[imageUrl.length - 1] && (imageUrl[imageUrl.length - 1] == 46 || imageUrl[imageUrl.length - 1] == 64 || imageUrl[imageUrl.length - 1] == 96 || imageUrl[imageUrl.length - 1] == 132)) {
      imageUrl[imageUrl.length - 1] = 0;
    }
    imageUrl = imageUrl.join('/'); //重新拼接为字符串
    return imageUrl;
  },



  drawImg(avatarUrl) {
    let that = this;
    console.log("-- drawImg --");
    // `${that.data.userInfo.avatarUrl}`
    let promise1 = new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: avatarUrl,
        success: function (res) {
          console.log("promise1", res)
          resolve(res);
        }
      })
    });
    var index = that.data.defaultImg;
    // ../../images/head${index}.png
    // hat0.png  avg.jpg
    let promise2 = new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: index,
        success: function (res) {
          console.log(res)
          resolve(res);
        }
      })
    });
    Promise.all([
      promise1, promise2
    ]).then(res => {
      console.log("Promise.all", res)
      //主要就是计算好各个图文的位置
      let num = 150;
      ctx.drawImage(res[0].path, this.cdx, 0, num, num)
      ctx.drawImage('../../' + res[1].path, this.cdx, 0, num, num)
      ctx.stroke()
      ctx.draw(false, () => {
        wx.canvasToTempFilePath({
          x: this.cdx,
          y: 0,
          width: num,
          height: num,
          destWidth: 960,
          destHeight: 960,
          canvasId: 'shareImg',
          success: function (res) {
            that.setData({
              prurl: res.tempFilePath
            })
            // wx.hideLoading()
          },
          fail: function (res) {
            wx.hideLoading()
          }
        })
      })
    })

  },

  save: function () {
    var that = this;
    if (!that.data.prurl) {
      wx.showToast({
        title: '请先生成专属头像',
      })
      return;
    }
    wx.saveImageToPhotosAlbum({
      filePath: that.data.prurl,
      success(res) {
        wx.showModal({
          content: '图片已保存到相册，赶紧晒一下吧~',
          showCancel: false,
          confirmText: '好哒',
          confirmColor: '#72B9C3',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定');
            }
          }
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取系统信息
    wx.getSystemInfo({
      success: res => {
        // 获取窗口宽高
        this.cdx = (res.windowWidth - 150) / 2
      }
    })
    this.setData({
      list: img.snow,
      hot: img.snow,
      national: img.national,
      defaultImg: img.snow[0]['url']
    })
    this.initCanvas(this.data.defaultImg)
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '领取你的专属头像',
      success: function (res) {
        // 转发成功
        console.log("转发成功:" + JSON.stringify(res));
      },
      fail: function (res) {
        // 转发失败
        console.log("转发失败:" + JSON.stringify(res));
      }
    }
  }
})